import { AssetCard, ProcessCard } from "@/components";
import {
  getUserToHouseContactRecordById,
  getWaitUserListBindHouse,
  getWorkflowList,
  updateUserToHouseContact,
  updateUserToHouseContactRecord,
} from "@/services";
import type {
  GetWaitUserListBindHouseReq,
  GetWorkflowListReq,
  WaitUserListBindHouse,
  WorkflowInfo,
} from "@/services";
import { useGetState, useSafeState } from "ahooks";
import React, { useEffect } from "react";
import { history, useSearchParams } from "umi";
import {
  Button,
  ErrorBlock,
  InfiniteScroll,
  Tabs,
  Steps,
  TextArea,
  Dialog,
  Toast,
} from "antd-mobile";
import { useUserStore } from "@/store";
import { trim } from "lodash-es";
import dayjs from "dayjs";

const { Step } = Steps;
interface ConcatUser {
  concatTime: string;
  content: string;
}

const UserVisitor: React.FC = () => {
  const [searchParams] = useSearchParams();
  const [visitorList, setVisitorList, getVisitorList] = useGetState<
    WaitUserListBindHouse[]
  >([]);
  const [workFlowList, setWorkFlowList] = useSafeState<WorkflowInfo[]>([]);
  const { userInfo, getUserInfo } = useUserStore();
  const [hasMore, setHasMore] = useSafeState(true);

  const [concatList, setConcatList, getConcatList] = useGetState<ConcatUser[]>(
    []
  );

  const getWorkflowListRequest = async () => {
    const userId = searchParams.get("userId");
    if (!userId) return;
    const req: GetWorkflowListReq = {
      title: "", // 业务标题
      busionessType: 2, // 业务类型1-卖房；2-买房
      homeName: "", // 房产名称
      userName: "", // 创建人
      nickName: "", // 用户昵称,微信昵称
      contactPerson: "", // 联系人
      tel: "", // 联系电话
      userId,
      // creator: userInfo.onlyId,
      page: 1,
      size: 100,
    };
    const res = await getWorkflowList(req);
    if (res.code == 200) {
      setWorkFlowList(res.data.list);
    }
  };

  const getUserVisitorRequest = async () => {
    const onlyId = searchParams.get("onlyId");
    if (!onlyId) return;
    const req: GetWaitUserListBindHouseReq = {
      unassignedId: onlyId, // 分配列表的id
      page: 1,
      size: 10,
    };
    const res = await getWaitUserListBindHouse(req);
    if (res.code === 200) {
      const newList = [...getVisitorList(), ...res.data.list];
      setHasMore(newList.length < res.data.total);
      setVisitorList(newList);
    }
  };

  const loadMore = async (isRetry: boolean) => {
    await getUserVisitorRequest();
  };

  const newProcessHandle = () => {
    const userId = searchParams.get("userId");
    history.push(`/modules/new-process?userId=${userId}`);
  };

  const getHisConcatListRequest = async () => {
    const onlyId = searchParams.get("onlyId");
    if (!onlyId) return;
    const res = await getUserToHouseContactRecordById({
      onlyId,
    });
    if (res.code == 200) {
      const hisConcatList = res.data.communicationRecord
        ? JSON.parse(res.data.communicationRecord)
        : [];
      setConcatList(hisConcatList);
    }
  };

  const newConcatRecordHandle = async () => {
    let content = "";
    const onlyId = searchParams.get("onlyId");
    if (!onlyId) return;
    const result = await Dialog.confirm({
      title: "填写联系内容",
      content: (
        <div className="border-b border-gray-1  border-solid h-170px flex px-10px rounded">
          <TextArea
            defaultValue={content}
            placeholder="请填写联系内容"
            autoSize={{ minRows: 4, maxRows: 6 }}
            onChange={(val) => {
              content = trim(val);
            }}
          />
        </div>
      ),
    });
    if (result) {
      const newConcatItem: ConcatUser = {
        content,
        concatTime: dayjs().format("YYYY-MM-DD HH:mm:ss"),
      };
      const newConcatList = [...getConcatList(), newConcatItem];
      // 创建或者更新
      if (getConcatList().length == 0) {
        const res = await updateUserToHouseContact({
          onlyId,
          communicationRecord: JSON.stringify(newConcatList),
        });
        if (res.code == 200) {
          Toast.show("创建成功");
          getHisConcatListRequest();
        }
      } else {
        const res = await updateUserToHouseContactRecord({
          onlyId,
          communicationRecord: JSON.stringify(newConcatList),
        });
        if (res.code == 200) {
          Toast.show("创建成功");
          getHisConcatListRequest();
        }
      }
    }
  };

  useEffect(() => {
    getUserInfo();
    getHisConcatListRequest();
  }, []);

  useEffect(() => {
    if (userInfo.onlyId) {
      getWorkflowListRequest();
    }
  }, [userInfo.onlyId]);

  return (
    <div className="bg-gray-1 min-h-100vh">
      <Tabs>
        <Tabs.Tab title="访问记录" key="record">
          <div className="max-h-[calc(100vh-120px)]  overflow-y-auto">
            {visitorList.map((item) => (
              <AssetCard key={item.onlyId} record={item} />
            ))}
            {visitorList.length === 0 && (
              <div className="mt-100px ">
                <ErrorBlock status="empty" title="暂无数据" description="" />
              </div>
            )}
            <InfiniteScroll loadMore={loadMore} hasMore={hasMore} />
          </div>
        </Tabs.Tab>
        <Tabs.Tab title="服务流程" key="process">
          <div className="max-h-[calc(100vh-120px)]  overflow-y-auto">
            {workFlowList.map((item, index) => (
              <ProcessCard
                key={index}
                record={item}
                processOver={() => {
                  getWorkflowListRequest();
                }}
              />
            ))}
            {workFlowList.length === 0 && (
              <div className="mt-100px ">
                <ErrorBlock status="empty" title="暂无数据" description="" />
              </div>
            )}
          </div>
        </Tabs.Tab>
        <Tabs.Tab title="客户跟进" key="concat">
          <div className="h-[calc(100vh-120px)]  overflow-y-auto bg-white">
            {concatList.map((item, index) => (
              <Steps
                direction="vertical"
                key={index}
                current={concatList.length - 1}
                style={{
                  "--title-font-size": "16px",
                  "--description-font-size": "15px",
                  "--indicator-margin-right": "6px",
                }}
              >
                <Step description={item.content} title={item.concatTime} />
              </Steps>
            ))}
            {concatList.length === 0 && (
              <div className="mt-100px ">
                <ErrorBlock status="empty" title="暂无数据" description="" />
              </div>
            )}
          </div>
        </Tabs.Tab>
      </Tabs>
      <div className="fixed bottom-0 h-60px w-full bg-white flex justify-around items-center">
        <Button
          className="w-170px h-50px"
          color="primary"
          onClick={() => newProcessHandle()}
        >
          新建服务流程
        </Button>
        <Button
          className="w-170px h-50px"
          color="primary"
          fill="outline"
          onClick={() => newConcatRecordHandle()}
        >
          新建联系记录
        </Button>
      </div>
    </div>
  );
};

export default UserVisitor;
